const categoryModel = require('../models/category.js');
const mongoose = require('mongoose');
const newsModel = require('../models/news.js');
const moment = require('moment');
const pagination = require('pagination');

class frNewsController {

	static getNewsList = async (req, res) => {
		/* 返回前台新闻信息 */
		const categoryInfo = await categoryModel.find();

		let gsCateId = '6129fe596b5eae44d038be2e';
		// console.log("req.query:", req.query);
		let cateId = req.query.cateId ? req.query.cateId : gsCateId;
		// console.log("cateId:", cateId);
		// 取得当前分类下所有的新闻
		const frinfos = await newsModel.aggregate([{
				$match: {
					cateId: mongoose.Types.ObjectId(cateId)
				}
			},
			{

				$lookup: {
					/*要关联的表 category*/
					from: "category",
					/*自己表里面和别的表产生关系的id*/
					localField: "cateId",
					/*关联表的id*/
					foreignField: "_id",
					/*查询到的关联信息的key值*/
					as: "cateInfo"
				}
			}
		]);
		let {
			page = 1, size = 2
		} = req.query;
		// res.json( req.query);
		page = parseInt(page);
		size = parseInt(size);
		let count = frinfos.length;
		let offset = (page - 1) * size;
		let totalPage = Math.ceil(count / size); // 小数 11条/2条 = 5.5 向上取整 5.3 = 6
		// console.log(page, size, count, offset, totalPage);
		//取得当前分类下每一页的新闻
		const infos = await newsModel.find({
			cateId
		}).limit(size).skip(offset);

		res.render('front/news', {
			categoryInfo,
			infos,
			cateId,
			moment,
			page,
			size,
			count,
			totalPage
		});
	}


	static detail = async (req, res) => {
		let newsId = req.params.newsId;
		const categoryInfo = await categoryModel.find();


		newsModel.findOne({
			_id: newsId
		}, async (error, doc) => {
			if (error) {
				res.render('error', {
					time: 3,
					url: 'front/news',
					errorRs: [error]
				});
			} else {
				doc.viewcount += 1;
				await doc.save();
				res.render('front/detail', {
					info: doc,
					moment,
					categoryInfo
				})
			}
		})

		/* 	let info = await newsModel.findOne({
				_id: newsId
			});
			res.render('front/detail', {
				info,
				moment,
			}); */
	};

}

module.exports = frNewsController;
